package com.xxx.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @version v1.0
 * @Description:
 * @Author zhanzhongxin
 * @Date 2021/8/6 15:57
 * @Copyright 博为峰
 */
@WebFilter("/*")
public class LoginFilter implements Filter {

    private List<String> urls = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext = filterConfig.getServletContext();
        String unCheckUrls = servletContext.getInitParameter("unCheckUrls");
        String[] array = unCheckUrls.split(",");
        urls = Arrays.asList(array);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        if (urls.contains(requestURI.substring(requestURI.lastIndexOf("/") + 1))) {
            filterChain.doFilter(request, response);
        } else {
            HttpSession session = request.getSession();
            if (session.getAttribute("username") != null)
                filterChain.doFilter(request, response);
            else
                response.sendRedirect(request.getContextPath() + "/login.jsp");
        }
    }

    @Override
    public void destroy() {
    }
}
